//
//  UIImage+Tool.swift
//  YuanJuBian
//
//  Created by PerhapYs on 2021/12/23.
//

import Foundation
import UIKit


/// 创建纯颜色图
/// - Parameters:
///   - color: 颜色
///   - size: 大小
/// - Returns: UIImage
func UIImageMake(With color:UIColor? , size:CGSize) -> UIImage?{
    
    guard let color = color else {
        return nil
    }
    let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
    
    if let context = UIGraphicsGetCurrentContext() {
        
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return resultImage
    }
    return nil
}

/// 创建视图色图
/// - Parameters:
///   - view: 视图
///   - size: 视图大小
/// - Returns: 颜色
func UIImageMake(with view:UIView , size:CGSize) -> UIImage?{
    
    UIGraphicsBeginImageContext(size)
    if let context = UIGraphicsGetCurrentContext() {
        view.layer .render(in: context)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        return image
    }
    return nil
}

extension String{
    
    /// Base64转图片
    /// - Returns: ～
    func base64StringImage() -> UIImage?{
        
        let imageData = Data.init(base64Encoded: self, options: .ignoreUnknownCharacters)
        if imageData != nil{
            return UIImage.init(data: imageData!)
        }
        return nil
    }
}
extension UIImage{
    
    /// 获取AVURLAsset的某一个事件的图片
    /// - Parameters:
    ///   - avaUrlAsset: 资源
    ///   - atTime: 时间点
    /// - Returns: ～
    class func image(of avaUrlAsset:AVURLAsset,atTime:TimeInterval = 0) -> UIImage?{
        
        let assetImageGenerator = AVAssetImageGenerator.init(asset: avaUrlAsset)
        assetImageGenerator.appliesPreferredTrackTransform = true
        assetImageGenerator.apertureMode = .encodedPixels

        let thumnailImageTime : CFTimeInterval = atTime
        let cmTime = CMTimeMake(value: Int64(thumnailImageTime), timescale: 60)
        
        var thumbnailImageRef : CGImage? = nil
        var thumbnailImage : UIImage? = nil
        do{
            thumbnailImageRef = try assetImageGenerator.copyCGImage(at: cmTime, actualTime: nil)
            thumbnailImage = thumbnailImageRef != nil ? UIImage.init(cgImage: thumbnailImageRef!) : nil
        }
        catch{
            debugPrint("获取AVURLAsset失败",error)
        }
        
        return thumbnailImage
    }
}
extension UIImage{
    
    /// 图片存储到缓存中，生成路径
    /// - Parameter pathComponent: 路径名
    /// - Returns: 图片路径
    func toTemporaryUrl(with pathComponent:String) -> String?{
        
        let image = self
        let temPath = FileManager.savePathOfTemp()
      
        var imagePath = temPath + pathComponent
        
        FileManager.createDirectory(at: imagePath)
        let fileName = Date.fileName(with: pathComponent, fileType: "jpg")
        imagePath = imagePath + fileName
        
        debugPrint("图片",imagePath)
        guard let imageData = image.toData(quality: 1.0) else {
            debugPrint("图片转Data失败")
            return nil
        }
        let saveUrl = URL.init(fileURLWithPath: imagePath)
        do{
            try imageData.write(to: saveUrl, options: .atomic)
            return imagePath
        }
        catch{
            debugPrint("图片",error)
            return nil
        }
    }
    
    /// 图片转DATA
    /// - Returns: DATA数据
    func toData(quality:CGFloat = 0.5) -> Data?{
        
       return self.jpegData(compressionQuality: quality)
    }
    /**
     *  重设图片大小
     */
    func  reSizeImage(reSize: CGSize )-> UIImage  {
        
        //UIGraphicsBeginImageContext(reSize);
        UIGraphicsBeginImageContextWithOptions (reSize, false , UIScreen.main.scale)
        draw(in: CGRect.init(x: 0, y: 0, width: reSize.width, height: reSize.height))
        let  reSizeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext ();
        return  reSizeImage!;
    }
    
    /**
     *  等比率缩放
     */
    func  scaleImage(scaleSize: CGFloat )-> UIImage  {
        
        let  reSize = CGSize.init(width: self.size.width * scaleSize, height: self.size.height*scaleSize)
        return  reSizeImage(reSize:reSize)
    }
    
    /// 点九图
    /// - Parameter insets: 延深位置
    /// - Returns: ～
    func resizingImage(_ insets:UIEdgeInsets) -> UIImage {
        
        let newImage = self.resizableImage(withCapInsets: insets, resizingMode: .stretch)
        return newImage
    }
    
    /// 生成渐变图片
    /// - Parameters:
    ///   - size: 渐变图片大小
    ///   - direction: 渐变方向
    ///   - colors: 渐变颜色
    ///   - locations: 渐变位置
    /// - Returns: 渐变图片
    class func gradientColor(with size:CGSize,cornerRadius:CGFloat = 0,direction:GradientColorDirection,colors:[UIColor],locations:[NSNumber]) -> UIImage?{
        
        guard let color = UIColor.gradientColor(with: size, cornerRadius: cornerRadius,direction: direction, colors: colors, locations: locations) else {
            return nil
        }
        return UIImageMake(With: color, size: size)
    }
}
